<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="资源名称" prop="name">
        <el-input
          v-model.trim="form.name"
          clearable
          placeholder="请输入资源名称"
        />
      </el-form-item>
      <el-form-item label="路径" prop="url">
        <el-input v-model.trim="form.url" clearable placeholder="请输入路径" />
      </el-form-item>
      <el-form-item label="资源类型" prop="type">
        <el-select v-model="form.type" clearable placeholder="请输入资源类型">
          <el-option
            v-for="item in typeOpt"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="父节点" prop="pid">
        <el-select
          v-model="form.pid"
          clearable
          :disabled="form.pid === 0"
          placeholder="请选择父节点"
        >
          <el-option
            :label="parentName"
            style="height: auto; padding: 0"
            :value="form.pid"
          >
            <el-tree
              ref="tree"
              :data="treeData"
              default-expand-all
              :props="defaultProps"
              @node-click="handleNodeClick"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model.trim="form.sort"
          clearable
          placeholder="请输入排序序号"
        />
      </el-form-item>
      <el-form-item label="资源图标" prop="icon">
        <el-input
          v-model.trim="form.icon"
          clearable
          placeholder="请输入资源图标名称"
        />
      </el-form-item>
      <el-form-item label="资源权限" prop="permission">
        <el-input
          v-model.trim="form.permission"
          clearable
          placeholder="请输入资源权限"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="isEnable">
        <el-radio-group v-model="form.isEnable">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="isSaving" type="primary" @click="save">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { addOrUpdateResource } from '@/api/resource'

  function getObjById(list, id) {
    //判断list是否是数组
    if (!Array.isArray(list)) {
      return null
    }
    //遍历数组
    for (let i in list) {
      let item = list[i]
      if (item.id === id) {
        return item
      } else {
        //查不到继续遍历
        if (Array.isArray(item.childList) && item.childList.length > 0) {
          let value = getObjById(item.childList, id)
          //查询到直接返回
          if (value) {
            return value
          }
        }
      }
    }
  }
  export default {
    name: 'ResourceEdit',
    props: {
      treeData: {
        type: Array,
        default: () => [],
        require: true,
      },
    },
    data() {
      const validateType = (rule, value, callback) => {
        if (typeof value === 'undefined') {
          callback(new Error('请选择资源类型'))
        } else {
          callback()
        }
      }
      const validatePid = (rule, value, callback) => {
        if (typeof value === 'undefined') {
          callback(new Error('请选择父节点'))
        } else {
          callback()
        }
      }
      return {
        defaultProps: {
          children: 'childList',
          label: 'name',
        },
        typeOpt: [
          { label: '顶级菜单', value: 0 },
          { label: '子菜单', value: 1 },
          { label: '按钮', value: 2 },
        ],
        parentName: '',
        form: {
          name: '',
          url: '',
          type: '',
          pid: null,
          permission: '',
          isEnable: 1,
        },
        rules: {
          name: [
            { required: true, message: '请输入资源名称', trigger: 'blur' },
          ],
          url: [{ required: true, message: '请输入资源路径', trigger: 'blur' }],
          type: [
            { required: true, validator: validateType, trigger: 'change' },
          ],
          pid: [{ required: true, validator: validatePid, trigger: 'change' }],
          permission: [
            { required: true, message: '请输入权限', trigger: 'blur' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        isSaving: false,
      }
    },
    methods: {
      handleNodeClick(node) {
        this.parentName = node.name
        this.form.pid = node.id
      },
      showEdit(row) {
        console.log(row)
        if (!row) {
          this.title = '添加资源'
        } else {
          this.title = '编辑资源'
          this.form = Object.assign({}, row)
          const item = getObjById(this.treeData, row.pid)
          if (item && item.name) {
            this.parentName = item.name
          } else {
            this.parentName = ''
          }
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.parentName = ''
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            try {
              this.isSaving = true
              const res = await addOrUpdateResource(this.form)
              console.log(this.form)
              let successMsg = '添加成功'
              let errorMsg = '添加失败'
              if (this.form.id) {
                successMsg = '修改成功'
                errorMsg = '修改成功'
              }
              if (res && res.status === 0) {
                this.$baseMessage(
                  res.msg || successMsg,
                  'success',
                  'vab-hey-message-success'
                )
                this.$emit('fetch-data')
                this.close()
              } else {
                this.$baseMessage(
                  res ? res.msg : errorMsg,
                  'error',
                  'vab-hey-message-error'
                )
              }
            } catch (e) {
              console.log(e)
              this.$baseMessage(
                e ? e.message : '操作失败',
                'error',
                'vab-hey-message-error'
              )
            }
            this.isSaving = false
          }
        })
      },
    },
  }
</script>
